#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <pthread.h>
struct ThreadInfo 
{
    int newsockfd_;
};

void* TcpThreadStart(void*arg)
{
    pthread_detach(pthread_self());
    struct ThreadInfo* ti = (struct ThreadInfo*)arg;
    int newsockfd = ti->newsockfd_;
    while(1)
    {
    //接收
    char buf[1024]={0};
    ssize_t recv_size =  recv(newsockfd,buf,sizeof(buf)-1,0);
    if(recv_size < 0)
    {
        perror("recv");
        continue;
    }
    else if(recv_size == 0)
    {
        printf("peer close connet\n");
        close(newsockfd);
        break;
    }
    printf("%s\n",buf);

    //发送
    memset(buf,'\0',sizeof(buf));
    strcpy(buf,"i am server!!!");
    send(newsockfd,buf,sizeof(buf)-1,0);
   }
}

int main()
{
    //创建套接字
    int listen_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(listen_sock < 0)
    {
        perror("socket");
        return 0;
    }
    //绑定地址
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(28989);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    int ret = bind(listen_sock,(struct sockaddr*)&addr,sizeof(addr));
    if(ret < 0)
    {
        perror("bind");
        return 0;
    }
    //监听
    ret = listen(listen_sock,1);
    if(ret < 0)
    {
        perror("listen");
        return 0;
    }


    while(1)
    {
        //接收新连接
        struct sockaddr_in cli_addr;
        socklen_t cli_addrlen = sizeof(cli_addr);
        int newsockfd =  accept(listen_sock,(struct sockaddr*)&addr,&cli_addrlen);
        if(newsockfd < 0)
        {
            perror("accept");
            return 0;
        }
        printf("accept new connect from client: %s:%d\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));

        struct ThreadInfo* ti = new ThreadInfo;
        ti->newsockfd_ = newsockfd;
        //创建线程
        pthread_t tid;
        ret = pthread_create(&tid,NULL,TcpThreadStart,(void*)ti);
        if(ret < 0)
        {
            close(newsockfd);
            delete ti;
            continue;
        }

    }
    close(listen_sock);
    return 0;
}
